package com.tjing.bussiness.controller;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author programmer
 * @since 2017年4月28日 下午8:28:16
 */
@Controller
@RequestMapping(value="/public/aliyun")
public class AliyunOSSController{
	private static final Logger LOGGER = LoggerFactory.getLogger(AliyunOSSController.class);
	private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS", Locale.CHINESE);
	// 创建ClientConfiguration实例，按照您的需要修改默认参数
	private static final ClientConfiguration CLIENT_CONFIGURATION = new ClientConfiguration();

	static {
		// 开启支持CNAME选项
		// CLIENT_CONFIGURATION.setSupportCname(true);// 默认已开启
	}

	private String endpoint="oss-cn-shenzhen.aliyuncs.com";

	private String accessKeyId="LTAIheZWWHN2jD8q";

	private String accessKeySecret="gYHk7ODv204lkkBmIsVTaSoQxDn8yT";

	private String bucketName="qhapp";

	/**
	 * @param file
	 * @return
	 * @author programmer
	 * @since 2017年4月28日 下午11:23:41
	 */
	@RequestMapping(value="/uploadimg")
	public @ResponseBody String uploadimg(@RequestParam("userfile") MultipartFile file) {
		System.out.println(file);
		if (file == null || file.isEmpty()) {
			//return new Result(30001, "没有文件上传过来");
			return "";
		}

		String contentType = file.getContentType();
		String originalFilename = file.getOriginalFilename();
		if (!contentType.matches("^image/(?:png|jpg|jpeg|gif|bmp)$")) {// 文件格式不匹配
			//return new Result(30001, "文件格式不匹配");
			return "";
		}

		OSSClient ossClient = null;
		try {
			// 工程中可以有多个OSSClient，也可以只有一个OSSClient；OSSClient可以并发使用；OSS支持https，当您的安全需求更高时，可以使用https；OSSClient.shutdown之后不能再使用。
			ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, CLIENT_CONFIGURATION);

			String ldt = LocalDateTime.now().format(DATE_TIME_FORMATTER);
			StringBuilder dt = new StringBuilder();
			dt.append(ldt.substring(0, 6)).append("/");
			dt.append(ldt.substring(6, 8)).append("/");
			dt.append(ldt.substring(8)).append(RandomStringUtils.randomAlphabetic(6));
			dt.append(originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length()));

			ossClient.putObject(bucketName, dt.toString(), file.getInputStream());

			StringBuilder data = new StringBuilder("http://");
			if (endpoint.lastIndexOf(".aliyuncs.com") > -1) {// 说明使用了OSS域名
				data.append(bucketName).append(".");// 返回的链接需追加bucketName
			}
			data.append(endpoint).append("/").append(dt);

			//return new Result(10000, "上传图片成功", data.toString());
			return data.toString();
		} catch (OSSException | ClientException | IOException e) {
			LOGGER.error(e.getMessage(), e);
			//return Result.error();
			return "";
		} finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}
	}
	@RequestMapping(value="/uploadapk")
	public @ResponseBody String uploadapk(@RequestParam("userfile") MultipartFile file) {
		if (file == null || file.isEmpty()) {
			//return new Result(30001, "没有文件上传过来");
			return "";
		}

		String contentType = file.getContentType();
		String originalFilename = file.getOriginalFilename();

		OSSClient ossClient = null;
		try {
			// 工程中可以有多个OSSClient，也可以只有一个OSSClient；OSSClient可以并发使用；OSS支持https，当您的安全需求更高时，可以使用https；OSSClient.shutdown之后不能再使用。
			ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, CLIENT_CONFIGURATION);

			String ldt = LocalDateTime.now().format(DATE_TIME_FORMATTER);
			StringBuilder dt = new StringBuilder();
			dt.append(ldt.substring(0, 6)).append("/");
			dt.append(ldt.substring(6, 8)).append("/");
			dt.append(ldt.substring(8)).append(RandomStringUtils.randomAlphabetic(6));
			dt.append(originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length()));

			ossClient.putObject(bucketName, dt.toString(), file.getInputStream());

			StringBuilder data = new StringBuilder("http://");
			if (endpoint.lastIndexOf(".aliyuncs.com") > -1) {// 说明使用了OSS域名
				data.append(bucketName).append(".");// 返回的链接需追加bucketName
			}
			data.append(endpoint).append("/").append(dt);

			//return new Result(10000, "上传图片成功", data.toString());
			return data.toString();
		} catch (OSSException | ClientException | IOException e) {
			LOGGER.error(e.getMessage(), e);
			//return Result.error();
			return "";
		} finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}
	}

	@RequestMapping(value="/appupload")
	public @ResponseBody Map appupload(@RequestParam("userfile") MultipartFile file) {
		Map resultMap = new HashMap();
		if (file == null || file.isEmpty()) {
			//return new Result(30001, "没有文件上传过来");
			resultMap.put("state", "1");
			resultMap.put("msg", "1");
			resultMap.put("data", new HashMap());
			return resultMap;
		}

		String contentType = file.getContentType();
		String originalFilename = file.getOriginalFilename();
		/*if (!contentType.matches("^image/(?:png|jpg|jpeg|gif|bmp)$")) {// 文件格式不匹配
			//return new Result(30001, "文件格式不匹配");
			resultMap.put("state", "1");
			resultMap.put("msg", "2");
			resultMap.put("data", new HashMap());
			return resultMap;
		}*/

		OSSClient ossClient = null;
		try {
			// 工程中可以有多个OSSClient，也可以只有一个OSSClient；OSSClient可以并发使用；OSS支持https，当您的安全需求更高时，可以使用https；OSSClient.shutdown之后不能再使用。
			ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, CLIENT_CONFIGURATION);

			String ldt = LocalDateTime.now().format(DATE_TIME_FORMATTER);
			StringBuilder dt = new StringBuilder();
			dt.append(ldt.substring(0, 6)).append("/");
			dt.append(ldt.substring(6, 8)).append("/");
			dt.append(ldt.substring(8)).append(RandomStringUtils.randomAlphabetic(6));
			dt.append(originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length()));

			ossClient.putObject(bucketName, dt.toString(), file.getInputStream());

			StringBuilder data = new StringBuilder("http://");
			if (endpoint.lastIndexOf(".aliyuncs.com") > -1) {// 说明使用了OSS域名
				data.append(bucketName).append(".");// 返回的链接需追加bucketName
			}
			data.append(endpoint).append("/").append(dt);

			Map resultMap1 = new HashMap();
			resultMap1.put("picUrl", data);
			resultMap.put("state", "1");
			resultMap.put("msg", "");
			resultMap.put("data", resultMap1);
			return resultMap;
		} catch (OSSException | ClientException | IOException e) {
			LOGGER.error(e.getMessage(), e);
			//return Result.error();
			resultMap.put("state", "1");
			resultMap.put("msg", "3");
			resultMap.put("data", new HashMap());
			return resultMap;
		} finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}
	}
}